/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.cereshop.app.controller.userAuth;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.app.service.faceCheck.FaceCheckService;
import com.shop.cereshop.app.service.userAuth.UserRealnameAuthService;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.commons.domain.im.tx.req.friend.FriendItem;
import com.shop.cereshop.commons.domain.im.tx.req.friend.GetFriendListReq;
import com.shop.cereshop.commons.domain.im.tx.resp.friend.FriendBaseResp;
import com.shop.cereshop.commons.domain.im.tx.resp.friend.FriendUserDataItem;
import com.shop.cereshop.commons.domain.user.faceCheck.FaceCheckModel;
import com.shop.cereshop.commons.domain.user.faceCheck.respond.FaceCheckRespond;
import com.shop.cereshop.commons.domain.userAuth.UserRealnameAuthRespond;
import com.shop.cereshop.commons.result.Result;
import com.shop.cereshop.commons.service.im.ImUserService;
import com.shop.cereshop.commons.utils.EmptyUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 用户实名认证表
 * </p>
 *
 * @author
 * @date 2025-08-07
 */
@Slf4j
@RestController
@RequestMapping("/userRealnameAuth")
@Api(value = "UserRealnameAuth", tags = "用户实名认证")
public class UserRealnameAuthController {

    @Resource
    private FaceCheckService faceCheckService;

    @Resource
    private CereBuyerUserService cereBuyerUserService;

    @Resource
    private UserRealnameAuthService userRealnameAuthService;

    @Resource
    private ImUserService imUserService;


    @GetMapping("getAuthInfo")
    @ApiOperation(value = "获取用户实名认证信息")
    public Result<UserRealnameAuthRespond> getAuthInfo(Long userId, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        CereBuyerUser user = null;
        if (!EmptyUtils.isEmpty(token)) {
            //根据token查询用户信息
            user = cereBuyerUserService.findByToken(token);
        }
        UserRealnameAuthRespond byUserId = userRealnameAuthService.findAuthInfoByUserId(userId);
        if (BeanUtil.isNotEmpty(byUserId)) {
            return new Result<UserRealnameAuthRespond>(byUserId, CoReturnFormat.SUCCESS);
        }
        return new Result<UserRealnameAuthRespond>("未查询到认证信息", "5001");
    }

    @PostMapping("userAuth")
    @ApiOperation(value = "用户实名认证  ")
    public Result<String> userAuth(@RequestBody FaceCheckModel model, HttpServletRequest request) {

        try {

            // 解密请求参数
            model = model.decrypt();
        } catch (Exception e) {
            return new Result<>(CoReturnFormat.PARAM_INVALID);
        }
        System.out.println(model.getName());
        String token = request.getHeader("Authorization");
        CereBuyerUser user = null;
        if (!EmptyUtils.isEmpty(token)) {
            //根据token查询用户信息
            user = cereBuyerUserService.findByToken(token);
        }
        FaceCheckRespond faceCheckRespond = faceCheckService.faceCheck(model);
        if (faceCheckRespond.getSuccess()) {
            Boolean i = userRealnameAuthService.saveUserAuth(user, faceCheckRespond, model);
            if (i) {
                return new Result<String>("success", CoReturnFormat.SUCCESS);
            }
        }
        return new Result<String>("认证失败 人像不符", "5002");
    }



    @PutMapping("/audit")
    @ApiOperation(value = "用户实名认证审核")
    public Result audit(@RequestParam Integer statue,@RequestParam Long userId) {
        if (statue==1){
        Integer number  =userRealnameAuthService.updateStatue(statue,userId);
        if (number>0) {
            return new Result(CoReturnFormat.SUCCESS);
        }
        }
      return new Result(CoReturnFormat.FAIL);

    }
    /**
     * 获取用户好友信息
     */
    @PostMapping("/friends")
    @ApiOperation(value = "获取用户好友信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", defaultValue = "1", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = true, defaultValue = "10", dataType = "Integer"),
            @ApiImplicitParam(name = "friendName", value = "好友名称", required = false, dataType = "String")
    })
    public Result<CereBuyerUser> getFriends(@RequestParam Integer page,
                                            @RequestParam Integer size,
                                            @RequestParam(required = false) String friendName,
                                            HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        CereBuyerUser user = null;
        if (!EmptyUtils.isEmpty(token)) {
            //根据token查询用户信息
            user = cereBuyerUserService.findByToken(token);
        } else {
            return new Result(false, CoReturnFormat.USER_NOT_LOGIN);
        }
        GetFriendListReq req = new GetFriendListReq();
        if (user != null) {
            req.setFromAccount(String.valueOf(user.getBuyerUserId()));
        }
        req.setStartIndex(0);
        FriendBaseResp<FriendItem> friendBaseResp = imUserService.getFriendList(req);
        if ("OK".equals(friendBaseResp.getActionStatus())) {
            List<FriendUserDataItem> userDataItem = friendBaseResp.getUserDataItem();
            if (CollUtil.isNotEmpty(userDataItem)) {
                //提取userDataItem中的所有的 To_Account 组成一个集合
                List<String> userIdList = userDataItem.stream().map(FriendUserDataItem::getTo_Account).collect(Collectors.toList());
                List<CereBuyerUser> userImportReqList = cereBuyerUserService.selectByBuyerUserIds(userIdList, friendName);
                return new Result(userImportReqList, CoReturnFormat.SUCCESS);
            }
        }
        return new Result(false);
    }
}
